package com.atsmart.app.exception;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Random;

import android.content.Context;

public class DefaultExceptionHandler implements Thread.UncaughtExceptionHandler {
    private Thread.UncaughtExceptionHandler defaultExceptionHandler;
    private GlobalExceptionInfo info;

    public DefaultExceptionHandler(
            Thread.UncaughtExceptionHandler paramUncaughtExceptionHandler,
            GlobalExceptionInfo info) {
        this.defaultExceptionHandler = paramUncaughtExceptionHandler;
        this.info = info;
    }

    public DefaultExceptionHandler(GlobalExceptionInfo info,
            Context paramContext) {
        this.defaultExceptionHandler = Thread
                .getDefaultUncaughtExceptionHandler();
        this.info = info;
    }

    public void uncaughtException(Thread paramThread, Throwable ex) {
        if (!handleException(ex) && defaultExceptionHandler != null) {
            this.defaultExceptionHandler.uncaughtException(paramThread, ex);
        } else {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {

            }
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(10);
        }

    }

    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return true;
        }
        collectCrashExceptionInfo(ex);
        return true;
    }

    private void collectCrashExceptionInfo(Throwable ex) {
        final Writer result = new StringWriter();
        final PrintWriter printWriter = new PrintWriter(result);
        ex.printStackTrace(printWriter);
        ex.printStackTrace();
        info.StackTraceMassage = result.toString();
        printWriter.close();
    }


    @SuppressWarnings("unused")
    private String getFileName() {
        Random localRandom = new Random();
        int i = localRandom.nextInt(99999);
        final String str = info.AppVersion + "-" + Integer.toString(i);
        return info.FilesPath + "/" + str + ".stacktrace";
    }

    @SuppressWarnings("unused")
    private void writeToFile(String filename) {
        try {
            BufferedWriter localBufferedWriter = new BufferedWriter(
                    new FileWriter(filename));
            localBufferedWriter.write(info.toJson());
            localBufferedWriter.flush();
            localBufferedWriter.close();
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }
}
